package com.taobao.dingtalk.client;

import java.time.Instant;
import java.util.Date;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.response.OapiGettokenResponse;

import cn.hutool.core.util.StrUtil;

public class DingTalkClientToken {
	Logger logger = LoggerFactory.getLogger(DingTalkClientToken.class);

	private String appid;

	private String appsecret;

	private Long agentid;

	private String token;

	private Date startTime;

	private Lock lock = new ReentrantLock();

	public DingTalkClientToken(String appid, String appsecret, Long agentid) {
		this.appid = appid;
		this.appsecret = appsecret;
		this.agentid = agentid;
	}

	public String getToken() {
		lock.lock();
		try {
			if (StrUtil.isBlank(this.token)) {
				logger.info("token为空,请求获取Token");
				accessDingTalk();
			} else {
				// 判断时间是否超时
				long curr = System.currentTimeMillis();
				long diff = curr - startTime.getTime();
				long five = 7100 * 1000;
				if (diff > five) {
					// 超时
					accessDingTalk();
				}
			}
		} finally {
			lock.unlock();
		}
		return token;
	}

	private void accessDingTalk() {
		logger.info("访问钉钉,获取Token");
		DefaultDingTalkClient defaultDingTalkClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
		OapiGettokenRequest request = new OapiGettokenRequest();
		request.setAppkey(this.appid);
		request.setAppsecret(this.appsecret);
		request.setHttpMethod("GET");
		try {
			OapiGettokenResponse response = defaultDingTalkClient.execute(request);
			// 判断系统code
			if (response.getErrcode() == -1) {
				// 服务不可用,重试一次
				accessDingTalk();
			} else if (response.getErrcode() == 0) {
				String tk = response.getAccessToken();
				this.token = tk;
				this.startTime = Date.from(Instant.now());
			}
		} catch (Exception e) {
			logger.error("获取Token失败,错误信息:{}", e.getMessage());
			logger.error(e.getMessage());
		}

	}

	public String getAppid() {
		return appid;
	}

	public String getAppsecret() {
		return appsecret;
	}

	public Long getAgentid() {
		return agentid;
	}
}
